/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Area;
import cn.net.ecode.modules.sys.service.AreaService;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 区域Controller
 * @author ThinkGem
 * @version 2014-8-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/area")
public class AreaController extends BaseController {

	@Autowired
	private AreaService areaService;
	
	@ModelAttribute
	public Area get(String areaCode, boolean isNewRecord) {
		return areaService.get(areaCode, isNewRecord);
	}

	@RequiresPermissions("sys:area:view")
	@RequestMapping(value = {"list", ""})
	public String list(Area area, Model model) {
		return "modules/sys/areaList";
	}
	
	/**
	 * 查询列表数据
	 * @param area
	 * @return
	 */
	@RequiresPermissions("sys:area:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public List<Area> listData(Area area) {
		if (StringUtils.isBlank(area.getParentCode())) {
			area.setParentCode(Area.ROOT_CODE);
		}
		List<Area> list = null;
		if (StringUtils.isNotBlank(area.getAreaCode())){
			list = Lists.newArrayList(get(area.getAreaCode(), false));
		}else{
			list = areaService.findList(area);
		}
		return list;
	}

	@RequiresPermissions("sys:area:view")
	@RequestMapping(value = "form")
	public String form(Area area, Model model) {
		if (StringUtils.isNotBlank(area.getParentCode())){
			area.setParent(areaService.get(area.getParentCode()));
		}
		model.addAttribute("area", area);
		return "modules/sys/areaForm";
	}
	
	@RequiresPermissions("sys:area:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(Area area, Model model) {
		if(Global.isDemoMode()){
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		StringBuilder builder = new StringBuilder();
		if (!beanValidator(builder, area)){
			return renderResult(Global.FALSE, builder.toString());
		}
		areaService.save(area);
		return renderResult(Global.TRUE, "保存区域'" + area.getAreaName() + "'成功");
	}
	
	@RequiresPermissions("sys:area:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(Area area, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		areaService.delete(area);
		return renderResult(Global.TRUE, "删除区域成功");
	}

	/**
	 * 获取区域JSON数据。
	 * @param extCode 排除的ID
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(String extCode, String isShowCode) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Area> list = areaService.findAll();
		for (int i=0; i<list.size(); i++){
			Area e = list.get(i);
			if (StringUtils.isBlank(extCode) || (extCode!=null && !extCode.equals(e.getAreaCode()) && e.getParentCodes().indexOf(","+extCode+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getAreaCode());
				map.put("pId", e.getParentCode());
				map.put("pIds", e.getParentCodes());
				if ("true".equals(isShowCode) || "1".equals(isShowCode)){
					map.put("name", "(" + e.getAreaCode() + ")" + e.getAreaName());
				}else if ("2".equals(isShowCode)){
					map.put("name", e.getAreaName() + "(" + e.getAreaCode() + ")");
				}else{
					map.put("name", e.getAreaName());
				}
				mapList.add(map);
			}
		}
		return mapList;
	}

	@RequiresPermissions("sys:area:edit")
	@ResponseBody
	@RequestMapping(value = "dataFix")
	public String dataFix(){
		areaService.updateFixParentCodes();
		return renderResult(Global.TRUE, "数据修复成功");
	}
}
